import 'dart:convert';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/controllers/main/login/http_const.dart';
import 'package:share_fit/app/controllers/main/login/login_logic.dart';
import 'package:share_fit/app/controllers/space/weekly/string_util.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/tools/color_const.dart';
import 'package:share_fit/app/ute/uteped_device.dart';
import 'package:share_fit/generated/locales.g.dart';

class LoginPage extends StatelessWidget {

  final logic = Get.put(LoginLogic());

  final FocusNode _focusNodeName = FocusNode();
  final FocusNode _focusNodePwd = FocusNode();
  String nameValue = '';
  String pwdValue = '';

  bool toMainPage = false;

  @override
  Widget build(BuildContext context) {
    // logic.setNameFocus(false);
    // logic.setPwdFocus(false);
    _focusNodeName.addListener(() {
      logic.setNameFocus(_focusNodeName.hasFocus);
    });
    _focusNodePwd.addListener(() {
      logic.setPwdFocus(_focusNodePwd.hasFocus);
    });

    if(Get.arguments!=null) {
      Map<String, dynamic> params = Get.arguments;
      if(params.containsKey('toMainPage')) {
        toMainPage = params['toMainPage'];
      }
    }
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        padding: EdgeInsets.only(top: 150.h),
        child: Column(
          children: [
            GestureDetector(
              onTap: (){
                  logic.save('login_state', false, global: true);
                  if(toMainPage) {
                    Get.back();
                    return;
                  }

                  logic.save('login_skip', true, global: true);
                  Get.offAllNamed('/main');
                },
              child: Container(
                width: 1.sw,
                padding: EdgeInsets.only(right: 48.sp),
                alignment: Alignment.centerRight,
                child: Text(LocaleKeys.login_skip.ts, style: TextStyle(fontSize: 42.sp, color: ColorConst.accentColor),),
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 82.h),
              alignment: Alignment.center,
              width: 285.w,
              height: 215.h,
              child: Image.asset('assets/images/home/ic_launcher.png'),
            ),
            // FutureBuilder<AppInfo>(
            //   future: InstalledApps.getAppInfo(appInfo['packageName']),
            //   builder:
            //       (BuildContext buildContext, AsyncSnapshot<AppInfo> snapshot) {
            //     return snapshot.connectionState == ConnectionState.done
            //         ? snapshot.hasData
            //         ?Column(
            //           children: [
            //             Container(
            //               margin: EdgeInsets.only(top: 82.h),
            //               alignment: Alignment.center,
            //               width: 285.w,
            //               height: 215.h,
            //               child: Image.memory(snapshot.data!.icon!),
            //             ),],)
            //         : Container(
            //             margin: EdgeInsets.only(top: 82.h),
            //             alignment: Alignment.center,
            //             width: 285.w,
            //             height: 215.h,)
            //         : Center();
            //   },),
            _getUsernameInput(),
            _getPasswordInput(),
            SizedBox(height: 50.h,),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                GestureDetector(
                  onTap: (){Get.offNamed('/login/sms');},
                  child: Container(
                    padding: EdgeInsets.only(left: 42.sp),
                    alignment: Alignment.centerRight,
                    child: Offstage(offstage: true, child: Text(LocaleKeys.login_sms_code.ts, style: TextStyle(fontSize: 42.sp, color: Color(0xFF666666)),),),
                  ),
                ),
                GestureDetector(
                  onTap: (){Get.toNamed('/login/reset');},
                  child: Container(
                    margin: EdgeInsets.only(right: 42.sp),
                    alignment: Alignment.centerRight,
                    child: Text(LocaleKeys.login_forget_password.ts, style: TextStyle(fontSize: 42.sp, color: Color(0xFF666666)),),
                  ),
                ),
              ],
            ),
            Container(
              height: 136.h,
              width: 1.sw,
              margin: EdgeInsets.fromLTRB(42.w, 95.h, 42.w, 0),
              child: ElevatedButton(
                onPressed: () {
                  if(nameValue.isEmpty) {
                    logic.showTips('', LocaleKeys.login_input_phone_email.ts);
                    return;
                  }
                  if(!HttpConst.email(nameValue)) {
                    logic.showTips('', LocaleKeys.email_error.ts);
                    return;
                  }
                  if(pwdValue.isEmpty) {
                    logic.showTips('', LocaleKeys.login_input_password.ts);
                    return;
                  }

                  if(!HttpConst.verifyPassword(pwdValue)) {
                    logic.showTips('', LocaleKeys.reset_password_tips.ts);
                    return;
                  }

                  if(!logic.state.isBottomSelected) {
                    logic.showTips('', LocaleKeys.check_bottom_protocol.ts);
                    return;
                  }

                  logic.showLoading();
                  UTEPedDevice.instance.getDeviceId().then((value) {
                    logic.tokens(value, nameValue, 'password', pwdValue, '', '', 0)
                        .then((value){
                          logic.cancelLoading();
                          if(value!='') {
                            Map map = jsonDecode('$value');
                            if(map['code']==200) {
                              String displayName = map['data']['user']['displayName'];
                              // if(isFromSpace) {
                              //   Get.back(result: {'space_person_name': displayName, 'user_id': '${map['data']['user']['id']}'});
                              // } else {
                              // }

                              Future.delayed(Duration.zero, () {
                                if(toMainPage) {
                                  Get.until((route) => Get.currentRoute=='/main');
                                } else {
                                  Get.offAllNamed('/main');
                                }
                              });

                              UTEPedDevice.instance.checkOnlineDevices();
                            } else {
                              int code = map['code'];
                              if(code == 401) {
                                logic.showTips('', LocaleKeys.user_name_and_password_mismatch.ts);
                              } else {
                                logic.showTips('', HttpConst.getCodeToString(map['code']));
                              }
                            }
                          } else {
                            logic.showTips('', 'Error');
                          }
                    });
                  });
                },
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(ColorConst.activeColor),
                    shape: MaterialStateProperty.all(RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)
                    ))
                ),
                child: Text(LocaleKeys.login.ts, style: TextStyle(fontSize: 48.sp, color: Colors.white, ),),
              ),),
            Container(
              height: 136.h,
              width: 1.sw,
              margin: EdgeInsets.fromLTRB(42.w, 71.h, 42.w, 0),
              child: ElevatedButton(
                onPressed: () {
                  Get.offNamed('/login/country', arguments: {'toMainPage': toMainPage});
                  // Get.offNamed('/login/register');
                },
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(ColorConst.secondaryFontColor),
                    shape: MaterialStateProperty.all(RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)
                    ))
                ),
                child: Text(LocaleKeys.login_register.ts, style: TextStyle(fontSize: 48.sp, color: Colors.white, ),),
              ),),
            Spacer(),
            Offstage(offstage: true, child: Text(LocaleKeys.login_third.ts, style: TextStyle(fontSize: 48.sp, color: Color(0xFF666666))),),
            Offstage(offstage: true, child: Container(
              margin: EdgeInsets.only(top: 87.h),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  _buildLoginIcon('assets/images/space/icon_login_qq.png', onTap: (){}),
                  _buildLoginIcon('assets/images/space/icon_login_wechat.png', onTap: (){}),
                  _buildLoginIcon('assets/images/space/icon_login_twitter.png', onTap: (){}),
                  _buildLoginIcon('assets/images/space/icon_login_facebook.png', onTap: (){}),
                  _buildLoginIcon('assets/images/space/icon_login_gmail.png', onTap: (){}),
                ],),),),
            GestureDetector(
              onTap: (){logic.setBottomChecked(!logic.state.isBottomSelected);},
              child: Container(
                margin: EdgeInsets.fromLTRB(42.w, 88.h, 0, 100.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    GetBuilder<LoginLogic>(
                        id: 'login_bottom_selected', builder: (_){
                      return Stack(
                        children: [
                          SizedBox(width: 42.w,),
                          Center(
                            child: Image.asset('assets/images/space/icon_login_unselected.png', width: 47.w, height: 47.h,),
                          ),
                          Opacity(opacity: logic.state.isBottomSelected?1:0, child: Center(
                            child: Image.asset('assets/images/space/icon_login_selected.png', width: 58.w, height: 45.h,),),)
                        ],
                      );
                    }),
                    SizedBox(width: 22.w,),
                    Expanded(child: RichText(text: TextSpan(
                        children: [
                          TextSpan(text: StringUtils.autoLineString(LocaleKeys.login_read.ts), style: TextStyle(fontSize: 42.sp, color: ColorConst.secondaryFontColor),),
                          TextSpan(text: StringUtils.autoLineString(LocaleKeys.login_agreement.ts),
                              style: TextStyle(fontSize: 42.sp, color: ColorConst.accentColor),
                              recognizer: TapGestureRecognizer()..onTap = (){
                                Get.toNamed('/space/setting/agreement');
                              }
                          ),
                          TextSpan(text: StringUtils.autoLineString(LocaleKeys.login_and.ts), style: TextStyle(fontSize: 42.sp, color: ColorConst.secondaryFontColor),),
                          TextSpan(text: StringUtils.autoLineString(LocaleKeys.login_private.ts),
                              style: TextStyle(fontSize: 42.sp, color: ColorConst.accentColor),
                              recognizer: TapGestureRecognizer()..onTap = (){
                                Get.toNamed('/space/setting/private');
                              }
                          ),
                        ]
                    ),)),
                    SizedBox(width: 42.w,),
                  ],
                ),
              ),
            )
          ],),),
    );
  }

  Widget _getUsernameInput(){
    return GetBuilder<LoginLogic>(
        id: 'login_name_focus',
        builder: (_){
          return Container(
            margin: EdgeInsets.fromLTRB(42.w, 200.h, 42.w, 0),
            child: Column(
              children: [
                TextField(
                  maxLines: 1,
                  focusNode: _focusNodeName,
                  // enableInteractiveSelection: false,
                  cursorColor: ColorConst.secondaryFontColor,
                  onChanged: (value) {
                    nameValue = value;
                  },
                  decoration: InputDecoration(
                    icon: Container(
                      alignment: Alignment.bottomCenter,
                      width: 60.w,
                      child: ColorFiltered(
                        colorFilter:ColorFilter.mode(logic.state.isFocusedName?ColorConst.accentColor:ColorConst.secondaryFontColor, BlendMode.srcATop),
                        child: Image.asset('assets/images/space/icon_login_name.png', width: 60.w, height: 60.w,),
                      ),
                      // child: Image.asset('assets/images/space/icon_login_name.png', width: 60.w, height: 60.w,),
                    ),
                    hintText: LocaleKeys.login_input_phone_email.ts,
                    hintStyle: TextStyle(color: logic.state.isFocusedName?ColorConst.accentColor:ColorConst.secondaryFontColor, fontSize: 42.sp),
                    border: InputBorder.none,
                  ),
                ),
                Divider(height: 1.h,)
              ],
            ),
          );
    });
  }

  Widget _getPasswordInput(){
    return GetBuilder<LoginLogic>(
        id: 'login_pwd_focus',
        builder: (_){
          return Container(
            margin: EdgeInsets.fromLTRB(42.w, 72.h, 42.w, 0),
            child: Column(
              children: [
                TextField(
                  maxLines: 1,
                  focusNode: _focusNodePwd,
                  // enableInteractiveSelection: false,
                  obscureText: logic.state.obscureText,
                  cursorColor: ColorConst.secondaryFontColor,
                  onChanged: (value) {
                    pwdValue = value;
                  },
                  decoration: InputDecoration(
                    icon: Container(
                      alignment: Alignment.bottomCenter,
                      width: 60.w,
                      child: ColorFiltered(
                        colorFilter:ColorFilter.mode(logic.state.isFocusedPwd?ColorConst.accentColor:ColorConst.secondaryFontColor, BlendMode.srcATop),
                        child: Image.asset('assets/images/space/icon_login_pwd.png', width: 60.w, height: 60.w,),
                      ),
                    ),
                    suffix: GestureDetector(
                      onTap: (){logic.setObscureText(!logic.state.obscureText);},
                      child: Container(
                        alignment: Alignment.bottomCenter,
                        width: 60.w,
                        child: Image.asset(!logic.state.obscureText?'assets/images/space/icon_login_pwd_visibility.png':'assets/images/space/icon_login_pwd_gone.png', width: 60.w, height: 60.w,),
                      ),
                    ),
                    hintText: LocaleKeys.login_input_password.ts,
                    hintStyle: TextStyle(color: logic.state.isFocusedPwd?ColorConst.accentColor:ColorConst.secondaryFontColor, fontSize: 42.sp),
                    border: InputBorder.none
                  ),
                ),
                Divider(height: 1.h,)
              ],
            ),
          );
        });
  }

  Widget _buildLoginIcon(String image, {onTap}) {
    Widget widget = Container(
      margin: EdgeInsets.only(right: 37.w),
      child: Ink(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(100),
        ),
        child: InkResponse(
          onTap: onTap,
          splashColor: ColorConst.activeColor,
          borderRadius: BorderRadius.circular(100),
          highlightShape: BoxShape.rectangle,
          highlightColor: ColorConst.activeColor,
          containedInkWell: true,
          child: Container(
            width: 138.w,
            height: 138.h,
            child: Center(
              child: Image.asset(image, width: 58.w, height: 68.h,),
            ),
          ),
        ),
      ),
    );
    return widget;
  }

}